<!-- 手动报表 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <div class="top topSubmitBtn">
        <el-button class="btn" type="primary" @click="add()" >添加报表</el-button>
        <el-date-picker size="small"  v-model="Time" clearable @change="timeChange" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['12:00:00']"></el-date-picker>
      </div>
      <div>
        <el-table border :data="tableData" style="width: 100%; margin: 15px 0">
            <el-table-column type="index" width="50" label="序号"></el-table-column>
            <el-table-column prop="TransTime" width="180" label="创建时间" align="left"></el-table-column>
            <el-table-column prop="RuleName" label="时间范围" width="360" align="left">
              <template slot-scope="scope">
                {{ scope.row.StartTime }}  -  {{ scope.row.EndTime }}
              </template>
            </el-table-column>
            <el-table-column prop="Status" label="生成状态" align="left">
              <template slot-scope="scope">
                <!-- {{ scope.row.Status === 0? '等待' : scope.row.Status === 1? '成功' :'失败' }} -->
                <span v-if="scope.row.Status === 0" style="color:#E6A23C;">等待</span>
                <span v-if="scope.row.Status === 1" style="color:#67C23A;">成功</span>
                <span v-if="scope.row.Status != 1 && scope.row.Status != 0" style="color:#909399;">失败</span>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="BackupStatus" label="生成时间" align="left"></el-table-column> -->
            <!-- <el-table-column prop="BackupStartTime" label="生成时间" align="left"></el-table-column> -->
            <el-table-column prop="Title" label="报表标题" align="left"></el-table-column>
            <el-table-column prop="AttachType" label="报表格式" align="left"></el-table-column>
            <el-table-column prop="Descp" label="报表备注" align="left"></el-table-column>
            <el-table-column width="100" label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" :disabled="scope.row.Status!=1"  @click="downloadClick(scope.row)" title="下载" icon="el-icon-download" circle></el-button>
                    <el-button size="mini"  :disabled="scope.row.GenerateState===0" @click="handleDelete(scope.row)" title="删除" type="danger" icon="el-icon-delete" circle></el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          :current-page='pageNum'
          :page-size='pageSize'
          background 
          layout="total, prev, pager, sizes, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-row>
    <el-dialog
      :close-on-press-escape=false
      title="添加报表"
      top="3%"
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="70%">
      <el-form label-width="150px" :model="departForm" :rules="rules" ref="departForm">
        <el-form-item label='时间条件：'>
          <el-date-picker v-model="departForm.Condition.StartTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" size="small" style="width:200px" placeholder="开始时间"></el-date-picker>
          <span> 至 </span>
          <el-date-picker v-model="departForm.Condition.EndTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" size="small" style="width:200px" placeholder="结束时间"></el-date-picker>
        </el-form-item>
        <el-form-item label='发送邮件：' prop="Email">
          <el-input size="small" v-model="departForm.Email" style="width:350px"></el-input>
          <span class="tips-style">  （填空表示不发送邮件，多个目标邮箱使用分号隔开）</span>
        </el-form-item>
        <el-form-item label='报表标题：' prop="Title">
          <el-input size="small" v-model="departForm.Title" style="width:350px"></el-input>
        </el-form-item>
        <el-form-item label='报表格式：' prop="">
          <el-radio-group v-model="departForm.AttachType">
            <el-radio label="pdf">pdf</el-radio>
            <el-radio label="docx">docx</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='备注信息：' prop="">
          <el-input size="small" v-model="departForm.Descp" style="width:350px"></el-input>
        </el-form-item>
        <el-form-item label='统计数据：' prop="">
          只显示前：<el-input size="small" v-model="departForm.Condition.SumCount" style="width:150px"><span slot="append">名</span></el-input>，明细只形成前：<el-input size="small" v-model.number="departForm.Condition.DetailLogCount" style="width:150px"><span slot="append">条</span></el-input>
          <span class="tips-style">（填0表示报表包括所有明细列表日志）</span>
        </el-form-item>
        <el-form-item label='运行概览：' prop="">
          <el-checkbox v-model="departForm.Content.RunStatus" :false-label="0" :true-label="1">形成设备运行概览报表数据</el-checkbox>
        </el-form-item>
        <el-form-item label='事件分析：' prop="">
          <span>严重性等级：</span>
          <el-select  size="small" v-model="departForm.Content.LogEvent.EventLevel" style="width:150px" placeholder="请选择严重性等级">
            <el-option :value="0" label="全部"/>
            <el-option :value="1" label="致命"/>
            <el-option :value="2" label="紧急"/>
            <el-option :value="3" label="重要"/>
            <el-option :value="4" label="监视"/>
            <el-option :value="5" label="普通"/>
            <el-option :value="6" label="通知"/>
          </el-select>
          
          <el-checkbox style="margin-left:20px" v-model="departForm.Content.LogEvent.SumByDate" :false-label="0" :true-label="1">形成事件按日趋势统计图</el-checkbox>
          <el-checkbox v-model="departForm.Content.LogEvent.SumByUser" :false-label="0" :true-label="1">形成事件终端用户分布统计图</el-checkbox>
          <el-checkbox v-model="departForm.Content.LogEvent.SumByType" :false-label="0" :true-label="1">形成事件类型分布统计图</el-checkbox>
          <el-checkbox v-model="departForm.Content.LogEvent.SumByLevel" :false-label="0" :true-label="1">形成事件严重性等级分布统计图</el-checkbox>
          <el-checkbox v-model="departForm.Content.LogEvent.Detail" :false-label="0" :true-label="1">形成事件明细日志</el-checkbox>
        </el-form-item>
        <el-form-item label='同步日志：' prop="">
          <el-checkbox v-model="departForm.Content.LogRsync.SumByDate" :false-label="0" :true-label="1">形成同步按日趋势统计图</el-checkbox>
          <el-checkbox v-model="departForm.Content.LogRsync.SumByUser" :false-label="0" :true-label="1">形成同步日志终端用户统计图</el-checkbox>
          <el-checkbox v-model="departForm.Content.LogRsync.SumByRule" :false-label="0" :true-label="1">形成同步日志规则统计图</el-checkbox>
          <el-checkbox v-model="departForm.Content.LogRsync.Detail" :false-label="0" :true-label="1">形成同步明细日志</el-checkbox>
        </el-form-item>
        <el-form-item label='转储日志：' prop="">
          <el-checkbox v-model="departForm.Content.LogDump.SumByDate" :false-label="0" :true-label="1">形成转储按日趋势统计图</el-checkbox>
          <el-checkbox v-model="departForm.Content.LogDump.SumByUser" :false-label="0" :true-label="1">形成转储日志终端用户统计图</el-checkbox>
          <el-checkbox v-model="departForm.Content.LogDump.Detail" :false-label="0" :true-label="1">形成转储明细日志</el-checkbox>
        </el-form-item>
        <el-form-item label='文件操作日志：' prop="">
          <el-checkbox v-model="departForm.Content.LogFileOpt.SumByDate" :false-label="0" :true-label="1">形成文件操作按日趋势统计图</el-checkbox>
          <el-checkbox v-model="departForm.Content.LogFileOpt.SumByUser" :false-label="0" :true-label="1">形成文件操作日志终端用户统计图</el-checkbox>
          <el-checkbox v-model="departForm.Content.LogFileOpt.Detail" :false-label="0" :true-label="1">形成文件操作明细日志</el-checkbox>
        </el-form-item>
        <el-form-item label='恶意文件日志：' prop="">
          <el-checkbox v-model="departForm.Content.LogVirus.SumByDate" :false-label="0" :true-label="1">形成恶意文件按日趋势统计图</el-checkbox>
          <el-checkbox v-model="departForm.Content.LogVirus.SumByUser" :false-label="0" :true-label="1">形成恶意文件终端用户统计图</el-checkbox>
          <el-checkbox v-model="departForm.Content.LogVirus.Detail" :false-label="0" :true-label="1">形成恶意文件明细日志</el-checkbox>
        </el-form-item>
        
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from "@/api/firstPage";
import { treeing, getTreeData, parseTime } from "@/utils/index.js";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  directives: { elDragDialog },
  data() {
    var validator = (rule, value, callback) =>{
      let regexp = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
      value = value.toString()
      let valdata = value.split(';')
      let data = valdata[valdata.length - 1]
      //格式是否符合要求
      let isCorrect = true
      //是否重复
      let isRepeat = false
      if (valdata.length) {
        for (let i = 0; i < valdata.length; i++) {
          if (regexp.test(valdata[i]) === false) {
            isCorrect = false
          }
        }
        // 每次输入的会立即放在valdata数组中,在查找数组中是否已经存在该元素的时候需要排除自身
        //即新加入数组的元素,所以循环到倒数第二个元素时停止
        for (let i = 0; i < valdata.length - 1; i++) {
          if (valdata[i] === data) {
            isRepeat = true
          }
        }
      }
      if (value === '') {
        return callback()
      } else if (!isCorrect) {
        callback(new Error('请输入正确的邮箱地址,邮箱之间用逗号隔开'))
      } else if (isRepeat) {
        callback(new Error('输入的邮箱地址不能重复'))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      departForm:{
        Title: "",
        Descp: "",
        AttachType:"pdf",
        Condition: {
            StartTime: "",
            EndTime: "",
            SumCount: 20,
            DetailLogCount: 0
        },
        Content: {
            RunStatus: 1,
            LogEvent: {
              EventLevel: 0,
              SumByDate: 1,
              SumByUser: 1,
              SumByType: 1,
              SumByLevel: 1,
              Detail: 0
            },
            LogRsync: {
                SumByDate: 1,
                SumByUser: 1,
                SumByRule: 1,
                Detail: 0
            },
            LogDump: {
                SumByDate: 1,
                SumByUser: 1,
                Detail: 0
            },
            LogFileOpt: {
                SumByDate: 1,
                SumByUser: 1,
                Detail: 0
            },
            LogVirus: {
                SumByDate: 1,
                SumByUser: 1,
                Detail: 0
            }
        },
        Email: []
      },
      options:[],
      Time:[],
      tableData: [],
      rules:{
        Email: [
          { required: false,validator: validator, trigger: 'blur'  }
        ],
        Title: [
          { required: true, trigger: 'blur', message:"请输入报表标题"  }
        ]
      },
      pageNum: 1,
      pageSize: 10,
      total: 0
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
  },
  // watch:{
  //   Time(val){
  //     console.log(val);
  //     if (val === null) {
  //       val = [];
  //     }
  //     this.getData();
  //   }
  // },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  methods: {
    async getData(){
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter:{
          StartTime:this.Time[0],
          EndTime:this.Time[1]
        }
      }
      const res = await connrequest('GetManualReport',data)
      this.tableData = res.Data
      this.tableData.map(item=>{
        item.TransTime = parseTime(item.TransTime)
        item.EndTime = parseTime(item.EndTime)
        item.StartTime = parseTime(item.StartTime)
      })
      this.total = res.Paging.TotalCount
    },
    timeChange(val){
      if (!val) {
        this.Time = []
        this.getData()
      }else{
        this.getData()
      }
    },
    add(){
      // this.departForm = {}
      // this.ParentID = 0
      // this.ParentName = []
      // this.options = this.tableData
      // this.$nextTick(()=>{
      //   this.$refs['departForm'].clearValidate()
      // })
      this.dialogVisible = true
    },
    handleEdit(item){
      this.$message.info('该功能还在开发中')
      return
      this.options = this.tableData
      this.$set(this.departForm, 'lastDepartmemt', item.ID)
      this.$set(this.departForm, 'departName', item.DepartmentName)
      this.dialogVisible = true
    },
    // 级联选项卡点击关闭下拉
    elCascaderOnlick(){
      let that = this;
      setTimeout(function() {
        document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
          el.onclick = function() {
            this.previousElementSibling.click();
            that.$refs.cascaderAddr.dropDownVisible = false;
          };
        });
      }, 100);
    },
    handleChange(item){
      if(item){
        this.ParentID  = item[item.length - 1]
        this.ParentName = this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels[0]
      }
    },
    async submit(){
      this.$refs['departForm'].validate( async(valid) => {
        if(valid){
          const data = {
            Data:this.departForm
          }
          const res = await connrequest('AddManualReport', data)
          if(res.Status.StatusCode === 0){
            this.$message({
              type: 'success',
              message: '手动报表添加成功'
            });
            this.getData()
            this.dialogVisible = false
          }
        }
      })
    },
    handleDelete(item){
      this.$confirm('此操作将永久删除该报表, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let data = {
          Data:{
            TransTime: item.TransTime
          }
        }
        const res = await connrequest('DelManualReport', data)
        if(res.Status.StatusCode === 0){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
          this.dialogVisible = false
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.pageNum = 1
      this.getData()
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.getData()
    }
  }
};
</script>
<style scoped lang='scss'>
/* @import url(); 引入css类 */
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
